package com.tanhua.server.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

import com.tanhua.common.exception.BusinessException;
import com.tanhua.common.pojo.Admin;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.server.service.SystemService;
import com.tanhua.server.vo.AdminVo;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;

@RestController
@RequestMapping("system/users")
public class SystemController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SystemService systemService;

    /**
     * 获取验证码
     * @param uuid  浏览器生成随机id
     * @param response
     * @throws IOException
     */
    @GetMapping("/verification")
    @NoAuthorization
    public void getVerification(@RequestParam String uuid, HttpServletResponse response) throws IOException {
        //定义图形验证码的长和宽,字符个数，干扰数量
        CircleCaptcha captcha  = CaptchaUtil.createCircleCaptcha(200, 100,4,1);
        BufferedImage image = captcha.getImage();
        //向redis中添加验证码，key为前端传来的uuid，值为验证码，超时时间为5分钟
        redisTemplate.opsForValue().set(uuid,captcha.getCode(), Duration.ofMinutes(5));
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

    /**
     * 登录
     * @param param
     * @return
     */
    @PostMapping("login")
    @NoAuthorization
    public ResponseEntity login(@RequestBody Map<String ,String> param){
        Map<String, Object> map = systemService.login(param);
        if (map != null){
            return ResponseEntity.ok(map);
        }

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 登出
     * @return
     */
    @PostMapping("logout")
    public ResponseEntity logout(){
        //登出:将前端传入的token删除
        systemService.logout();
        return ResponseEntity.ok(null);
    }

    /**
     * 用户基础信息:用户名,用户id和头像
     * @return
     */
    @PostMapping("profile")
    public  ResponseEntity profile(){
        AdminVo adminVo= systemService.profile();
        return ResponseEntity.ok(adminVo);
    }

}
